package com.yuerenjf.yuerenjinfu.adapter;

import android.app.Activity;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.qiniu.android.utils.StringUtils;
import com.yuerenjf.yuerenjinfu.R;
import com.yuerenjf.yuerenjinfu.activity.MainActivity;
import com.yuerenjf.yuerenjinfu.activity.WebActivity;
import com.yuerenjf.yuerenjinfu.bean.LendYouXuanBean;
import com.yuerenjf.yuerenjinfu.bean.MainDataBean;
import com.yuerenjf.yuerenjinfu.customview.AutoVerticalScrollTextView;
import com.yuerenjf.yuerenjinfu.utils.DaysTimer;
import com.yuerenjf.yuerenjinfu.widget.DinTextView;

import org.greenrobot.eventbus.EventBus;
import org.xutils.common.util.LogUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.iwgang.countdownview.CountdownView;

/**
 * Created by Administrator on 2016/7/7.
 */
public class AdapterHomeRecyler2 extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int TYPE_HEADER = 0;
    private static final int TYPE_NORMAL = 1;
    private static final int TYPE_FOOTER = 2;
    private static final int NOTIFY = 2;

    private static final int STATUS_YURE = 1;
    private static final int STATUS_CHUJIE = 2;
    private static final int STATUS_YISHOUQING = 3;
    private static final int STATUS_JIXIZHONG = 4;
    private static final int STATUS_WANBI = 5;
    private static final int STATUS_ZHUANRANG = 6;


    private final SparseArray<HomeHolder> mCountdownVHList;
    private Handler mHandler = new Handler();
    private Timer mTimer;
    private boolean isCancel = true;


    private List<MainDataBean.DataBean.CurBorrowsBean> mDatas = new ArrayList<>();

    private View mHeaderView;
    private View mFootView;
    private TextView textView;

    private OnItemClickListener mListener;
    //    int position;
    private Activity mActivity;

    public AdapterHomeRecyler2(Activity mActivity) {
        this.mActivity = mActivity;
        mCountdownVHList = new SparseArray<>();
    }

    public void setOnItemClickListener(OnItemClickListener li) {
        mListener = li;
    }

    public void setHeaderView(View headerView) {
        mHeaderView = headerView;
        notifyItemInserted(0);
    }

    private int getHeadViewSize() {
        return mHeaderView == null ? 0 : 1;
    }

    public void setFootView(View footView) {
        mFootView = footView;
        notifyItemInserted(getHeadViewSize() + mDatas.size());
    }

    public View getHeaderView() {
        return mHeaderView;
    }

    public void addDatas(List<MainDataBean.DataBean.CurBorrowsBean> datas) {
        mDatas.addAll(datas);
        notifyDataSetChanged();
    }

    public void removeDatas() {
        mDatas.removeAll(mDatas);
    }

    @Override
    public int getItemViewType(int position) {
        int size = mDatas.size();
        if (position < getHeadViewSize()) {
            return TYPE_HEADER;
        } else if (position >= size + getHeadViewSize()) {
            return TYPE_FOOTER;
        }
        return TYPE_NORMAL;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (mHeaderView != null && viewType == TYPE_HEADER) {
            return new TopHolder(mHeaderView);
        } else if (viewType == TYPE_NORMAL) {
            View layout = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_lend_other_youxuan, parent, false);
            return new HomeHolder(layout);
        } else {
            View v = mFootView;
            return new FooterHolder(v);
        }

    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int position) {
//        this.position = position;
        if (viewHolder instanceof TopHolder) {
        } else if (viewHolder instanceof HomeHolder) {
            final MainDataBean.DataBean.CurBorrowsBean bean = getRealPosition(position);
            HomeHolder itemHolder = (HomeHolder) viewHolder;
            itemHolder.bindData(bean);
            itemHolder.mItem_lend_title.setText(bean.getBorrow_title());
            //抵押债权
            // itemHolder.mItem_lend_diya_status.settext
//
//            //新手专享
//            if (bean.getIs_new_hand() != null && bean.getIs_new_hand().equals("1")) {
//                itemHolder.mItem_lend_xinshou_status.setVisibility(View.VISIBLE);
//            } else {
//                itemHolder.mItem_lend_xinshou_status.setVisibility(View.GONE);
//            }
            if (StringUtils.isNullOrEmpty(bean.getAdd_apr_show())) {
                itemHolder.mItem_lend_shouyilv_top.setVisibility(View.INVISIBLE);
            } else {
                itemHolder.mItem_lend_shouyilv_top.setVisibility(View.VISIBLE);
                itemHolder.mItem_lend_shouyilv_top.setText(bean.getAdd_apr_show());
            }

            itemHolder.mItem_lend_first_shouyi_text.setText(bean.getApr() + "");
            if (!"0".equals(bean.getAdd_apr())) {
                itemHolder.mItem_lend_second_shouyi_text.setVisibility(View.VISIBLE);
                itemHolder.mItem_lend_second_shouyi_text.setText("+" + bean.getAdd_apr() + "%");
            } else {
                itemHolder.mItem_lend_second_shouyi_text.setVisibility(View.GONE);
            }
            itemHolder.mItem_lend_qixian_text.setText(bean.getTime_limit());
            itemHolder.mItem_lend_qixian_unit_text.setText(bean.getStyle());

            itemHolder.mItem_lend_total_text.setText(bean.getAccount() + "");

            itemHolder.mItem_lend_youxuan_last_money_text.setText("剩余" + bean.getNeed_accout() + "元可投");

            itemHolder.mItem_lend_percent_text.setText(bean.getDegree() + "%");
            Double d = Double.valueOf(bean.getDegree());
            long l = Math.round(d);
            int i = Math.round(l);
            itemHolder.mItem_lend_percent_pb.setProgress(i);

            switch (STATUS_CHUJIE) {
                case STATUS_YURE:
                    itemHolder.mItem_lend_youxuan_sell_status_text.setVisibility(View.GONE);
                    itemHolder.mCountDownView.setVisibility(View.VISIBLE);
                    long duration = bean.getTime_now() - System.currentTimeMillis() / 1000;//服务器与本地相差秒数
                    bean.setCountdown(duration);


                    long restTime = Long.valueOf(bean.getTime_start()) - bean.getTime_now();

                    itemHolder.mCountDownView.setmRemainTime(restTime * 1000);
                    LogUtil.i(restTime + "");
                    if (restTime > 0) {
                        synchronized (mCountdownVHList) {
                            mCountdownVHList.put(Integer.valueOf(bean.getBorrow_id()), itemHolder);
                        }
                        startRefreshTime();
                    } else {
//                        bean.setButton_status(STATUS_CHUJIE);
                        notifyDataSetChanged();
                    }


                    break;

                case STATUS_CHUJIE:
                    itemHolder.mItem_lend_youxuan_sell_status_text.setBackgroundResource(R.drawable.icon_lend_status_btn);
                    itemHolder.mItem_lend_youxuan_sell_status_text.setText("立即购买");
                    itemHolder.mItem_lend_youxuan_sell_status_text.setVisibility(View.VISIBLE);
                    itemHolder.mCountDownView.setVisibility(View.GONE);
                    break;


                case STATUS_YISHOUQING:
                    itemHolder.mItem_lend_youxuan_sell_status_text.setBackgroundResource(R.drawable.icon_lend_status_btn_gray);
                    itemHolder.mItem_lend_youxuan_sell_status_text.setText("已售罄");
                    itemHolder.mItem_lend_youxuan_sell_status_text.setVisibility(View.VISIBLE);
                    itemHolder.mCountDownView.setVisibility(View.GONE);
                    break;

                case STATUS_JIXIZHONG:
                    itemHolder.mItem_lend_youxuan_sell_status_text.setBackgroundResource(R.drawable.icon_lend_status_btn_gray);
                    itemHolder.mItem_lend_youxuan_sell_status_text.setText("正在计息中");
                    itemHolder.mItem_lend_youxuan_sell_status_text.setVisibility(View.VISIBLE);
                    itemHolder.mCountDownView.setVisibility(View.GONE);
                    break;

                case STATUS_WANBI:
                    itemHolder.mItem_lend_youxuan_sell_status_text.setBackgroundResource(R.drawable.icon_lend_status_btn_gray);
                    itemHolder.mItem_lend_youxuan_sell_status_text.setText("还款已完毕");
                    itemHolder.mItem_lend_youxuan_sell_status_text.setVisibility(View.VISIBLE);
                    itemHolder.mCountDownView.setVisibility(View.GONE);
                    break;

                case STATUS_ZHUANRANG:
                    itemHolder.mItem_lend_youxuan_sell_status_text.setBackgroundResource(R.drawable.icon_lend_status_btn_gray);
                    itemHolder.mItem_lend_youxuan_sell_status_text.setText("已转让");
                    itemHolder.mItem_lend_youxuan_sell_status_text.setVisibility(View.VISIBLE);
                    itemHolder.mCountDownView.setVisibility(View.GONE);
                    break;


            }

            itemHolder.mItem_lend_youxuan_sell_status_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    WebActivity.launchActivity(mActivity, bean.getBorrow_url());
                }
            });
            itemHolder.mCountDownView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    WebActivity.launchActivity(mActivity,bean.getBorrow_url());
                }
            });


            if (mListener == null) return;
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mListener.onItemClick(position, bean);
                }
            });
        } else if (viewHolder instanceof FooterHolder)

        {
            ((FooterHolder) viewHolder).moreText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                    Toast.makeText(mActivity,"查看更多",Toast.LENGTH_LONG).show();
                    MainActivity mainActivity = (MainActivity) mActivity;
                    if (mainActivity.getContentFragment() != null) {
                        mainActivity.getContentFragment().setTabSelected(1);
//                        MainTabFragment fragmentHaitao= (MainTabFragment)mainActivity.getmCurrentFragment();
//                        fragmentHaitao.selectFragment(1);
//                        fragmentHaitao.
                        ;
                        EventBus.getDefault().post(
                                new FirstEvent("FirstEvent btn clicked"));
                    } else {
                        Toast.makeText(mActivity, "出错了", Toast.LENGTH_LONG).show();
                    }

                }
            });
        }


    }

    private void countDown(TextView textView, long millisInFuture) {

        DaysTimer daysTimer = new DaysTimer(textView, millisInFuture, 1000);
        daysTimer.start();
    }

    public MainDataBean.DataBean.CurBorrowsBean getRealPosition(int position) {
        return mDatas.get(position - getHeadViewSize());
    }

    /**
     * 以下两个接口代替 activity.onStart() 和 activity.onStop(), 控制 timer 的开关
     */

    private int getFooterViewSize() {
        return mFootView == null ? 0 : 1;
    }

    @Override
    public int getItemCount() {
        int count = 0;
        int size = mDatas.size();
        count = getHeadViewSize() + size + getFooterViewSize();
        return count;
    }

    @Override
    public void onViewRecycled(RecyclerView.ViewHolder holder) {
        super.onViewRecycled(holder);
        if (holder instanceof HomeHolder) {
            HomeHolder homeHolder = (HomeHolder) holder;
            MainDataBean.DataBean.CurBorrowsBean curAnnounceGoodsInfo = homeHolder.getmItemInfo();
            if (null != curAnnounceGoodsInfo && Long.valueOf(curAnnounceGoodsInfo.getTime_start()) - System.currentTimeMillis() > 0) {
                mCountdownVHList.remove(Integer.valueOf(curAnnounceGoodsInfo.getBorrow_id()));
            }

        }
    }


    class HomeHolder extends RecyclerView.ViewHolder {
        private TextView mItem_lend_diya_status;
        private TextView mItem_lend_xinshou_status;
        private TextView mItem_lend_title;
        private TextView mItem_lend_shouyilv_top;
        private DinTextView mItem_lend_first_shouyi_text;
        private DinTextView mItem_lend_second_shouyi_text;
        private TextView mItem_lend_total_text;
        private TextView mItem_lend_total_unit_text;
        private TextView mItem_lend_youxuan_last_money_text;
        private ProgressBar mItem_lend_percent_pb;
        private TextView mItem_lend_youxuan_sell_status_text;


        private DinTextView mItem_lend_qixian_text;
        private TextView mItem_lend_qixian_unit_text;
        private TextView mItem_lend_percent_text;
        private CountdownView mCountDownView;

        public CountdownView getmCountDownView() {
            return mCountDownView;
        }

        public void setmCountDownView(CountdownView mCountDownView) {
            this.mCountDownView = mCountDownView;
        }

        MainDataBean.DataBean.CurBorrowsBean mItemInfo;

        public MainDataBean.DataBean.CurBorrowsBean getmItemInfo() {
            return mItemInfo;
        }

        public void setmItemInfo(MainDataBean.DataBean.CurBorrowsBean mItemInfo) {
            this.mItemInfo = mItemInfo;
        }

        public HomeHolder(View itemView) {
            super(itemView);

            mItem_lend_diya_status = (TextView) itemView.findViewById(R.id.item_lend_diya_status);
            mItem_lend_xinshou_status = (TextView) itemView.findViewById(R.id.item_lend_xinshou_status);
            mItem_lend_title = (TextView) itemView.findViewById(R.id.item_lend_title);
            mItem_lend_shouyilv_top = (TextView) itemView.findViewById(R.id.item_lend_shouyilv_top);
            mItem_lend_first_shouyi_text = (DinTextView) itemView.findViewById(R.id.item_lend_first_shouyi_tv);
            mItem_lend_second_shouyi_text = (DinTextView) itemView.findViewById(R.id.item_lend_second_shouyi_text);
            mItem_lend_total_text = (TextView) itemView.findViewById(R.id.item_lend_total_text);
            mItem_lend_total_unit_text = (TextView) itemView.findViewById(R.id.item_lend_total_unit_text);
            mItem_lend_youxuan_last_money_text = (TextView) itemView.findViewById(R.id.item_lend_youxuan_last_money_text);
            mItem_lend_percent_pb = (ProgressBar) itemView.findViewById(R.id.pb_newlevel);
            mItem_lend_youxuan_sell_status_text = (TextView) itemView.findViewById(R.id.item_lend_youxuan_sell_status_text);

            mItem_lend_qixian_text = (DinTextView) itemView.findViewById(R.id.item_lend_qixian_tv);
            mItem_lend_qixian_unit_text = (TextView) itemView.findViewById(R.id.item_lend_qixian_unit_tv);
            mItem_lend_percent_text = (TextView) itemView.findViewById(R.id.item_lend_persent_tv);
            mCountDownView = (CountdownView) itemView.findViewById(R.id.countDownView);

        }

        public void bindData(MainDataBean.DataBean.CurBorrowsBean itemInfo) {
            mItemInfo = itemInfo;
        }

        public void refreshTime() {
            if (null == mItemInfo || mCountDownView.getRemainTime() <= 0)
                return;
            mCountDownView.updateShow((Long.valueOf(mItemInfo.getTime_start()) - System.currentTimeMillis() / 1000 + mItemInfo.getCountdown()) * 1000);
        }
    }

    public interface OnItemClickListener {
        void onItemClick(int position, MainDataBean.DataBean.CurBorrowsBean data);
    }

    public String formatDiscount(double d) {
        String s = String.valueOf(d);
        if (d * 10 % 10 == 0) {
            s = s.substring(0, s.indexOf("."));
        }
        return s;
    }

    class TopHolder extends RecyclerView.ViewHolder {

//        private TextView moreText;
//        private AutoVerticalScrollTextView mAutoVerticalScrollText;

        public TopHolder(View itemView) {
            super(itemView);
//            moreText= (TextView) itemView.findViewById(R.id.footview_more_text);
//            mAutoVerticalScrollText= (AutoVerticalScrollTextView) itemView.findViewById(R.id.find_news_item_title_text);
        }
    }

    class FooterHolder extends RecyclerView.ViewHolder {

        private TextView moreText;
        private AutoVerticalScrollTextView mAutoVerticalScrollText;

        public FooterHolder(View itemView) {
            super(itemView);
            moreText = (TextView) itemView.findViewById(R.id.footview_more_text);
            mAutoVerticalScrollText = (AutoVerticalScrollTextView) itemView.findViewById(R.id.find_news_item_title_text);
        }

    }

    private String fomatData(long l) {
        return String.format("%02d", l);
    }


    public void startRefreshTime() {
        if (!isCancel) return;
        if (null != mTimer) {
            mTimer.cancel();
        }

        isCancel = false;
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                mHandler.post(mRefreshTimeRunnable);
            }
        }, 0, 1000);
    }

    public void cancelRefreshTime() {
        isCancel = true;
        if (null != mTimer) {
            mTimer.cancel();
        }
        mHandler.removeCallbacks(mRefreshTimeRunnable);
    }

    private Runnable mRefreshTimeRunnable = new Runnable() {
        @Override
        public void run() {
            if (mCountdownVHList.size() == 0) return;

            synchronized (mCountdownVHList) {
                long currentTime = System.currentTimeMillis()/1000;
                Log.i("restTime","currentTime"+currentTime+"-----");
                int key;
                for (int i = 0; i < mCountdownVHList.size(); i++) {
                    key = mCountdownVHList.keyAt(i);
                   HomeHolder curMyViewHolder = mCountdownVHList.get(key);
                    long a=curMyViewHolder.getmCountDownView().getRemainTime()/1000;
                    if (a<=0) {
                        // 倒计时结束
//                        curMyViewHolder.getmItemInfo().setTime_start("0");

                        Log.i("restTime","倒计时结束");
                        mCountdownVHList.remove(key);
//                        curMyViewHolder.getmItemInfo().setButton_status(STATUS_CHUJIE);
                        notifyDataSetChanged();

                    } else {
                        curMyViewHolder.refreshTime();
                    }

                }
            }
        }
    };
}